import asyncio
import aiomysql
from config import br_mysql_conf
from base.logcontrol import logger
from base.tools import wrapper


class AsyncMysql(object):

    def __init__(self):
        self.conf = br_mysql_conf
        self.sql = None

    def __repr__(self):
        return "AsyncMysql对象"

    async def get_data(self):
        try:
            pool = await aiomysql.create_pool(host=self.conf.get("host"),
                                              port=self.conf.get("port"),
                                              user=self.conf.get("user"),
                                              password=self.conf.get("password"),
                                              charset="utf8")
            async with pool.acquire() as conn:
                async with conn.cursor() as cur:
                    await cur.execute(self.sql)
                    r = await cur.fetchall()
            pool.close()
            await pool.wait_closed()
        except Exception as e:
            logger.error(f"\n发生异常：{e}\n")
            raise RuntimeError()
        return r

    @wrapper
    def exec(self, sql):
        self.sql = sql
        r = asyncio.run(self.get_data())
        return r
